<template>
  <div class="device-management-list">
    <el-card>
      <div slot="header" class="card-header">
        <span>设备管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加设备
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="所属区域">
            <el-select v-model="searchForm.areaId" placeholder="请选择区域" style="width: 180px">
              <el-option v-for="area in areaList" :key="area.id" :label="area.areaName" :value="area.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称" style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="table-container">
        <el-table v-loading="loading" :data="deviceList" stripe style="width: 100%">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="180"></el-table-column>
          <el-table-column prop="areaName" label="所属区域" width="150"></el-table-column>
          <el-table-column prop="ipAddress" label="IP地址" width="150"></el-table-column>
          <el-table-column prop="description" label="设备描述">
            <template slot-scope="scope">
              <el-popover placement="top" title="设备描述" width="400" trigger="hover">
                <p>{{ scope.row.description }}</p>
                <div slot="reference" class="description-tooltip">
                  <span>{{ scope.row.description && scope.row.description.length > 50 ? scope.row.description.substring(0, 50) + '...' : (scope.row.description || '-') }}</span>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" :formatter="dateFormat"></el-table-column>
          <el-table-column label="数据库数量" width="100" :formatter="dbCountFormat"></el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-dropdown size="small">
                <el-button size="small" type="text">
                  <i class="el-icon-setting"></i> 操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleEdit(scope.row)">
                    <i class="el-icon-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleViewDatabases(scope.row)">
                    <i class="el-icon-database"></i> 查看数据库
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="handleDelete(scope.row)">
                    <i class="el-icon-delete"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DeviceManagementList',
  data() {
    return {
      deviceList: [],
      areaList: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchForm: {
        areaId: '',
        deviceName: ''
      }
    };
  },
  mounted() {
    // 页面加载时获取区域列表
    this.getAreaList();
    // 检查URL参数中的areaId
    const areaId = this.$route.query.areaId;
    if (areaId) {
      this.searchForm.areaId = areaId;
    }
    // 获取设备列表
    this.getDeviceList();
  },
  methods: {
    // 获取区域列表
    getAreaList() {
      this.$api.areaApi.getAll().then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        this.areaList = data && data.data || [];
      }).catch(err => {
        console.error('获取区域列表失败:', err);
        this.$message.error('获取区域列表失败，请稍后重试');
        this.areaList = [];
      });
    },
    
    // 获取设备列表
    getDeviceList() {
      this.loading = true;
      // 构建查询参数
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
        ...this.searchForm
      };
      
      this.$api.deviceApi.getAll(params).then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        const deviceData = data && data.data || [];
        // 为每个设备添加区域名称
        this.deviceList = deviceData.map(device => {
          // 根据areaId从areaList中查找对应的区域名称
          const area = this.areaList.find(area => area.id === device.areaId);
          return {
            ...device,
            areaName: area ? area.areaName : '-' // 如果找不到对应区域，显示'-'
          };
        });
        this.total = deviceData.length;
      }).catch(err => {
        console.error('获取设备列表失败:', err);
        this.$message.error('获取设备列表失败，请稍后重试');
        this.deviceList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 添加设备
    handleAdd() {
      this.$router.push('/device-management/add');
    },
    
    // 编辑设备
    handleEdit(row) {
      this.$router.push({ path: '/device-management/edit/' + row.id });
    },
    
    // 查看数据库
    handleViewDatabases(row) {
      this.$router.push({ path: '/database-config?deviceId=' + row.id });
    },
    
    // 删除设备
    handleDelete(row) {
      this.$confirm('确定要删除这个设备吗？删除后该设备下的所有数据库也将被删除。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            this.$api.deviceApi.delete(row.id).then(data => {
              this.$message.success('删除成功');
              this.getDeviceList(); // 重新加载列表
            }).catch(err => {
          console.error('删除设备失败:', err);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.getDeviceList();
    },
    
    // 重置搜索条件
    handleReset() {
      this.searchForm = {
        areaId: '',
        deviceName: ''
      };
      this.currentPage = 1;
      this.getDeviceList();
    },
    
    // 刷新列表
    handleRefresh() {
      this.getDeviceList();
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getDeviceList();
    },
    
    // 当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getDeviceList();
    },
    
    // 日期格式化
    dateFormat(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        return date.toLocaleString('zh-CN');
      }
      return '';
    },
    
    // 数据库数量格式化
    dbCountFormat(row) {
      return row.dbCount || 0;
    }
  }
};
</script>

<style scoped>
.device-management-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
}

.search-container {
  margin-top: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-container {
  margin-top: 20px;
}

.description-tooltip {
  cursor: pointer;
  color: #409eff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>